package net.java.mediasystems.web.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;

import net.java.mediasystems.database.core.model.Metadata;
import net.java.mediasystems.database.core.service.MetadataService;

public class MetadataConverter implements Converter {
	
	private List<Metadata> metadataList;
	
	private MetadataService metadataService;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (!StringUtils.isEmpty(value)) {
			for (Metadata curMetadata : this.metadataList) {
				if (curMetadata.getId().longValue() == Long.parseLong(value)) {
					return curMetadata;
				}
			}
		}
		return null;
	}
	
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		Metadata metadataDefinition = (Metadata) value;
		return metadataDefinition.getId().toString();
	}
	
	/**
	 * Add the given Metadata to the MetadataList, used by the Converter.
	 * <br/>
	 * This Method has to be called, if a new Metadata got inserted into the Database, 
	 * and therefore the converter has to be extended by this new Element.
	 * 
	 * @param MetadataDefinition Metadata
	 */
	public void addNewMetadataDefinition(Metadata MetadataDefinition) {
		this.metadataList.add(MetadataDefinition);
	}
	
	/**
	 * Special Set()-Method: The MetadataList will be initialized immediately after setting the MetadataService.
	 * 
	 * @param metadataService MetadataService
	 */
	public void setMetadataService(MetadataService metadataService) {
		this.metadataService = metadataService;
		this.metadataList = this.metadataService.getAllMetadataDefinitions();
	}

}
